 
xquery version "1.0";

module namespace iatistats="http://iatiui.ampdev.net/iatistats";

import module namespace request="http://exist-db.org/xquery/request";
import module namespace session="http://exist-db.org/xquery/session";
import module namespace util="http://exist-db.org/xquery/util";

import module namespace iatistoring="http://iatiui.ampdev.net/iatistoring" at "storing.xql";


declare function iatistats:create_cache ($type as xs:string) {

	let $filename := concat($type,".xml"),
	$result := (<results>
		{
		for $org in distinct-values(collection('/db/iAG/xml')/iati-activities/iati-activity/reporting-org/@ref)
			let $orgName := subsequence(collection('/db/iAG/xml')/iati-activities/iati-activity/reporting-org[@ref=$org]/text(),1,1)
			  return 
				if ( compare($type,'feeds')=0  ) then 
				  let $num := count(collection('/db/iAG/xml')/iati-activities[iati-activity/reporting-org/@ref=$org])
					return <entry><key>{$orgName}</key><value>{$num}</value></entry>
				else 
					let $num := count(collection('/db/iAG/xml')/iati-activities/iati-activity[reporting-org/@ref=$org])
					return <entry><key>{$orgName}</key><value>{$num}</value></entry>
		}
		</results>
	)
	return iatistoring:write_cache($filename, $result)
};

declare function iatistats:cached_stats ($type as xs:string) as element() *{
	let $filename := concat($type,".xml"),
	$path := concat('/db',$iatistoring:CACHE_PATH,"/",$filename)
	return document($path)/results/entry
};

declare function iatistats:stats ($type as xs:string) as element() *{
  for $org in distinct-values(collection('/db/iAG/xml')/iati-activities/iati-activity/reporting-org/@ref)
  let $orgName := subsequence(collection('/db/iAG/xml')/iati-activities/iati-activity/reporting-org[@ref=$org]/text(),1,1)
  return 
	if ( compare($type,'feeds')=0  ) then 
	  let $num := count(collection('/db/iAG/xml')/iati-activities[iati-activity/reporting-org/@ref=$org])
		return <entry><key>{$orgName}</key><value>{$num}</value></entry>
	else 
		let $num := count(collection('/db/iAG/xml')/iati-activities/iati-activity[reporting-org/@ref=$org])
		return <entry><key>{$orgName}</key><value>{$num}</value></entry>
};

